package cn.gov.mwr.sl651;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;

import cn.gov.mwr.sl651.utils.ByteUtil;
import cn.gov.mwr.sl651.utils.CRC16Helper;

public class MessageGenerator {

	protected String startBit = "7E7E";
	protected String centerAddr = "01";
	protected String stationAddr;
	protected String password = "9999";
	protected String funcCode = "32";// 这个不能只用字节
	protected byte upDown;
	protected String bodyStartBit = "02";
	protected byte[] bodyCount;
	protected String eof = "03";

	protected String builderCrc(String message) {

		String crc = CRC16Helper.crc16Check(message);
		return crc;

	}

	public String buildBodySize(int length) {

		// 1000表示下行，0000表示上行
		byte up = (byte) (((byte) (0 & 0x0f)) << 4);
		byte[] lenByte = ByteUtil.ushortToBytes(length);
		byte low4 = (byte) (lenByte[0] & 0x0f);
		byte first = (byte) (up | low4);

		return ByteUtil.toHexString(new byte[] { first, lenByte[1] });
	}

	/**
	 * 
	 * @param serial
	 *            流水号,两个字节
	 * @param sendDate
	 *            发报时间
	 * @param stcd
	 *            测站编码
	 * @param sttp
	 *            测站类型
	 * @param viewtime
	 *            观测时间
	 * @param itemflag
	 *            观测标识符
	 * @param itemvalue
	 *            观测值
	 * @return
	 */
	public String buildBody(int serial, String sendDate, String stcd,
			String sttp, String viewtime, String itemflag, String itemvalue) {

		StringBuffer sb = new StringBuffer(100);

		/**
		 * 1、流水号
		 * 
		 * 取值范围：2字节HEX码，范围1～65535
		 */
		sb.append(ByteUtil.toHexString(ByteUtil.ushortToBytes(serial)));

		/**
		 * 2、发报时间
		 */
		// public String sendDate;
		sb.append(sendDate);

		/**
		 * 3、遥测站地址
		 */

		byte[] StationAddrSymbol = new byte[] { (byte) 0xF1, (byte) 0xF1 }; // F1H
		sb.append(ByteUtil.toHexString(StationAddrSymbol));
		sb.append(StringUtils.leftPad(stcd, 10, '0'));// 遥测站地址，占用5个字节

		/**
		 * 4、遥测站分类码
		 */
		sb.append(sttp);

		/**
		 * 5、观测时间
		 */
		sb.append("F0F0");
		sb.append(viewtime);// // 观测时间，占用5个字节

		/**
		 * 6、观测要素
		 */
		Random ra = new Random();
		if (StringUtils.equalsIgnoreCase(sttp, "48")) {
			sb.append("F460");
			for (int i = 0; i < 12; i++) {
				sb.append(StringUtils.leftPad("" + ra.nextInt(19), 2, '0'));
			}
		} else {
			sb.append("F5F5");
			for (int i = 0; i < 12; i++) {
				sb.append(StringUtils.leftPad("" + ra.nextInt(1999), 4, '0'));
			}
		}

		return sb.toString();
	}

	public String build(String stationAddr, String body) {
		StringBuffer sb = new StringBuffer(100);
		sb.append(this.startBit);
		// HEX报文
		sb.append(this.centerAddr);
		sb.append(stationAddr);

		sb.append(this.password);
		sb.append(this.funcCode);
		sb.append(buildBodySize(body.length() / 2));
		sb.append(this.bodyStartBit);
		sb.append(body);

		sb.append(this.eof);

		String crc = builderCrc(sb.toString());

		return sb.toString().toUpperCase() + crc.toUpperCase();
	}

	public static void main(String[] args) {

		String stcd = "12345678";

		SimpleDateFormat sdfSendDate = new SimpleDateFormat("yyMMddhhmmss");
		SimpleDateFormat sdfViewDate = new SimpleDateFormat("yyMMddhhmm");

		System.out.println(">> " + Class.class.getClass().getResource("/").getPath());
		
		String curPath = Class.class.getClass().getResource("/").getPath();
		String stationFile = curPath + "station.txt";
		System.out.println(">> stationFile " +stationFile);
		
		MessageGenerator gen = new MessageGenerator();

		stcd = StringUtils.leftPad(stcd, 10, '0');

		for (int i = 0; i < 10; i++) {
			String sendDate = sdfSendDate.format(new Date());
			String body = gen.buildBody(i, sendDate, stcd, "48",
					sdfViewDate.format(new Date()), "", "");
			String msg = gen.build(stcd, body);
			System.out.println(">> msg " + msg);
		}
		
		System.out.println(">>OK ");
	}

}
